<template>
  <div class="generic-service">
    <!-- 导航头部 -->
    <el-card class="nav-card" shadow="never">
      <div class="nav-content">
        <el-button 
          type="primary" 
          size="large" 
          class="full-width-btn"
          @click="$router.push({ path: '/work-log', query: { serviceId: serviceId, serviceName: serviceName } })"
        >
          <el-icon><EditPen /></el-icon>
          <span>记录{{ serviceName }}</span>
        </el-button>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <el-card class="stats-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><TrendCharts /></el-icon>
          <span>本月统计</span>
        </div>
      </template>

      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-number">{{ monthStats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ monthStats.pending }}</div>
          <div class="stat-label">待完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ Math.round(monthStats.progress) }}%</div>
          <div class="stat-label">完成率</div>
        </div>
      </div>
    </el-card>

    <!-- 工作记录列表 -->
    <el-card class="records-card" shadow="never">
      <template #header>
        <div class="card-header">
          <el-icon><Document /></el-icon>
          <span>{{ serviceName }}记录</span>
        </div>
      </template>

      <div v-if="records.length === 0" class="empty-state">
        <el-empty description="暂无记录" />
      </div>

      <div v-else class="record-list">
        <div 
          v-for="record in records" 
          :key="record.id"
          class="record-item"
          @click="viewDetail(record)"
        >
          <div class="record-header">
            <div class="record-client">{{ record.client?.clientName || '未知客户' }}</div>
            <div class="record-date">{{ record.completionDate ? formatDate(record.completionDate) : '待完成' }}</div>
          </div>
          <div class="record-content">
            <p>{{ record.workContent || '暂无详情' }}</p>
            <div v-if="record.client?.clientCode" class="client-info">
              <span class="client-code">客户编号：{{ record.client.clientCode }}</span>
              <span v-if="record.client?.terminalType" class="terminal-type">{{ record.client.terminalType }}</span>
            </div>
          </div>
          <div class="record-footer">
            <el-tag :type="getStatusType(record.status)" size="small">
              {{ getStatusText(record.status) }}
            </el-tag>
          </div>
        </div>
      </div>

      <div v-if="hasMore" class="load-more">
        <el-button 
          @click="loadMore" 
          :loading="loading" 
          text
          type="primary"
        >
          {{ loading ? '加载中...' : '加载更多' }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { EditPen, TrendCharts, Document } from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const route = useRoute()
const router = useRouter()

// 从路由参数获取服务信息
const serviceName = ref(decodeURIComponent(route.params.serviceName as string))
const serviceId = ref<number | null>(null)

// 重置组件状态
const resetComponentState = () => {
  serviceName.value = decodeURIComponent(route.params.serviceName as string)
  serviceId.value = null
  records.value = []
  currentPage.value = 1
  hasMore.value = true
  monthStats.value = {
    completed: 0,
    pending: 0,
    progress: 0
  }
}

// 数据状态
const records = ref<any[]>([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 20

// 统计数据
const monthStats = ref({
  completed: 0,
  pending: 0,
  progress: 0
})

// 格式化日期
const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '待完成'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'pending':
      return 'warning'
    case 'cancelled':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'pending':
      return '进行中'
    case 'cancelled':
      return '已取消'
    default:
      return '未知'
  }
}

// 查看详情
const viewDetail = (record: any) => {
  // 如果是待完成的记录，跳转到工作日志页面进行记录
  if (record.status === 'pending') {
    router.push({ 
      path: '/work-log', 
      query: { 
        serviceId: serviceId.value, 
        serviceName: serviceName.value,
        clientId: record.client?.id,
        clientName: record.client?.clientName
      } 
    })
    return
  }
  
  // 根据不同服务类型跳转到对应的详情页
  const pathMap: Record<string, string> = {
    '客户拜访': '/client-visit/detail',
    '诚信五化建设': '/integrity-building/detail',
    '客户评价': '/client-evaluation/detail',
    '满意度调查': '/satisfaction-survey/detail',
    '四员协同': '/team-collaboration/detail',
  }
  
  const detailPath = pathMap[serviceName.value] || '/work-log'
  router.push({ 
    path: detailPath, 
    query: { 
      logId: record.id,
      from: 'service'
    } 
  })
}

// 加载数据
const loadData = async () => {
  const user = AuthUtils.getUser<any>()
  if (!user?.id) return

  loading.value = true
  try {
    // 1. 获取服务ID（如果还没有）
    if (!serviceId.value) {
      const serviceList = await trpc.service.list.query({ pageSize: 100 })
      if (serviceList?.success) {
        const services = serviceList.data.data || serviceList.data || []
        const service = services.find((s: any) => s.serviceName === serviceName.value)
        if (service) {
          serviceId.value = service.id
        }
      }
    }

    // 2. 使用serviceStats API获取完整的客户和统计信息
    if (serviceId.value) {
      const now = new Date()
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
      const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)

      const statsResponse = await trpc.workLog.serviceStats.query({
        managerId: user.id,
        serviceId: serviceId.value,
        startDate: monthStart.toISOString(),
        endDate: new Date(monthEnd.getFullYear(), monthEnd.getMonth(), monthEnd.getDate(), 23, 59, 59, 999).toISOString()
      })

      if (statsResponse?.success) {
        const stats = statsResponse.data
        
        // 更新统计数据
        monthStats.value = {
          completed: stats.completedCount || 0,
          pending: stats.uncompletedCount || 0,
          progress: (stats.completedCount || 0) > 0 ? 
            Math.round(((stats.completedCount || 0) / ((stats.completedCount || 0) + (stats.uncompletedCount || 0))) * 100) : 0
        }

        // 构建记录列表：包括已完成和未完成的客户
        const allClientRecords = []
        
        // 添加已完成的客户记录（从recentLogs获取）
        if (stats.recentLogs && stats.recentLogs.length > 0) {
          stats.recentLogs.forEach((log: any) => {
            allClientRecords.push({
              id: log.id,
              client: log.client,
              completionDate: log.completionDate,
              workContent: log.notes || '已完成服务',
              status: 'completed'
            })
          })
        }

        // 添加未完成的客户记录
        if (stats.uncompletedClients && stats.uncompletedClients.length > 0) {
          stats.uncompletedClients.forEach((client: any) => {
            allClientRecords.push({
              id: `uncompleted_${client.id}`,
              client: client,
              completionDate: null,
              workContent: '待完成服务',
              status: 'pending'
            })
          })
        }

        // 按页面分页处理
        const startIndex = (currentPage.value - 1) * pageSize
        const endIndex = startIndex + pageSize
        const paginatedRecords = allClientRecords.slice(startIndex, endIndex)

        if (currentPage.value === 1) {
          records.value = paginatedRecords
        } else {
          records.value.push(...paginatedRecords)
        }
        
        hasMore.value = allClientRecords.length > currentPage.value * pageSize
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = async () => {
  currentPage.value++
  await loadData()
}

// 监听路由参数变化
watch(
  () => route.params.serviceName,
  (newServiceName, oldServiceName) => {
    if (newServiceName && newServiceName !== oldServiceName) {
      resetComponentState()
      loadData()
    }
  }
)

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.generic-service {
  padding: 20px;
  padding-bottom: 80px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.nav-card {
  margin-bottom: 20px;
}

.nav-content {
  padding: 10px 0;
}

.full-width-btn {
  width: 100%;
  height: 50px;
  font-size: 1.1rem;
}

.stats-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  text-align: center;
}

.stat-item {
  padding: 15px 0;
}

.stat-number {
  font-size: 1.8rem;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  color: #666;
}

.records-card {
  margin-bottom: 20px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.record-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.record-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-client {
  font-weight: 600;
  color: #333;
}

.record-date {
  font-size: 0.9rem;
  color: #666;
}

.record-content {
  margin: 8px 0;
}

.record-content p {
  color: #555;
  font-size: 0.9rem;
  margin: 0 0 8px 0;
  line-height: 1.4;
}

.client-info {
  display: flex;
  gap: 12px;
  font-size: 0.8rem;
  color: #666;
}

.client-code {
  color: #409EFF;
}

.terminal-type {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
  color: #606266;
}

.record-footer {
  display: flex;
  justify-content: flex-end;
}

.load-more {
  text-align: center;
  margin-top: 20px;
  padding: 20px;
}
</style>